package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExcelUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysCustomerMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户档案Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-09
 */
@Service
public class SysCustomerServiceImpl implements ISysCustomerService
{
    @Autowired
    private SysCustomerMapper sysCustomerMapper;

    /** 预约记录service接口层 */
    @Autowired
    private ISysAppointmentRecordService sysAppointmentRecordService;

    /** 追踪记录service接口层 */
    @Autowired
    private ISysStrackService sysStrackService;

    /** 信息大类service接口层 */
    @Autowired
    private ISourceOfLeadCustomersService sourceOfLeadCustomersService;

    /** 信息小类service接口层 */
    @Autowired
    private ISourceSubcategoryService sourceSubcategoryService;

    /**
     * 查询客户档案
     *
     * @param customerId 客户档案主键
     * @return 客户档案
     */
    @Override
    public SysCustomer selectSysCustomerByCustomerId(Long customerId)
    {
        SysCustomer sysCustomer = sysCustomerMapper.selectSysCustomerByCustomerId(customerId);
        if (null == sysCustomer){
            throw new RuntimeException("未查询到线索客户详情，请联系管理员");
        }
        //查询预约详情
        List<SysAppointmentRecord> sysAppointmentRecords = sysAppointmentRecordService.selectSysAppointmentRecordByCustomerId(customerId);
        if (!CollectionUtils.isEmpty(sysAppointmentRecords)){
            sysCustomer.setAppointmentRecordList(sysAppointmentRecords);
        }
        //查询追踪记录
        List<SysStrack> sysStracks = sysStrackService.selectSysStrackByCustomerId(customerId);
        if (!CollectionUtils.isEmpty(sysStracks)){
            sysCustomer.setStrackList(sysStracks);
        }

        return sysCustomer;
    }

    /**
     * 查询客户档案列表
     *
     * @param sysCustomer 客户档案
     * @return 客户档案
     */
    @Override
    public List<SysCustomer> selectSysCustomerList(SysCustomer sysCustomer)
    {
        return sysCustomerMapper.selectSysCustomerList(sysCustomer);
    }

    /**
     * 上传文件并新增线索客户方法
     * @param file
     * @return
     */
    @Override
    @Transactional
    public int uploadExcel(MultipartFile file) {
        if (file.isEmpty()){
            throw new RuntimeException("文件不能为空");
        }

        int status = 0;

        try {
            List<SysCustomer> sysCustomerList = new ArrayList<>();
            //解析Excel
            List<List<String>> data = ExcelUtil.parseExcel(file);
            for (int i = 0;i < data.size();i++){
                if (data.size() >= 3 && i != 0 && i != 1){
                    List<String> strings = data.get(i);
                    //构建实体
                    SysCustomer sysCustomer = new SysCustomer();
                    //判空
                    for (int j = 0;j < strings.size();j++){
                        //年级
                        if (j == 0){
                            if (StringUtils.isNotEmpty(strings.get(0))){
                                String grade = strings.get(0);
                                //小一
                                if (grade.equals("小一")){
                                    sysCustomer.setGrade(0L);
                                }
                                //小二
                                else if (grade.equals("小二")) {
                                    sysCustomer.setGrade(1L);
                                }
                                //小三
                                else if (grade.equals("小三")){
                                    sysCustomer.setGrade(2L);
                                }
                                //小四
                                else if (grade.equals("小四")) {
                                    sysCustomer.setGrade(3L);
                                }
                                //小五
                                else if (grade.equals("小五")){
                                    sysCustomer.setGrade(4L);
                                }
                                //小六
                                else if (grade.equals("小六")){
                                    sysCustomer.setGrade(5L);
                                }
                                //初一
                                else if (grade.equals("初一")){
                                    sysCustomer.setGrade(6L);
                                }
                                //初二
                                else if (grade.equals("初二")){
                                    sysCustomer.setGrade(7L);
                                }
                                //初三
                                else if (grade.equals("初三")){
                                    sysCustomer.setGrade(8L);
                                }
                                //高一
                                else if (grade.equals("高一")){
                                    sysCustomer.setGrade(9L);
                                }
                                //高二
                                else if (grade.equals("高二")){
                                    sysCustomer.setGrade(10L);
                                }
                                //高三
                                else if (grade.equals("高三")){
                                    sysCustomer.setGrade(11L);
                                }
                                else if (grade.equals("高四")){
                                    sysCustomer.setGrade(12L);
                                }
                            }
                        }
                        //姓名
                        else if (j == 1){
                            if (StringUtils.isEmpty(strings.get(1))){
                                throw new RuntimeException("姓名未填写");
                            }
                            sysCustomer.setCustomerName(strings.get(1));
                        }
                        //家庭住址
                        else if (j == 2){
                            if (StringUtils.isNotEmpty(strings.get(2))){
                                sysCustomer.setAddress(strings.get(2));
                            }
                        }
                        //电话
                        else if (j == 3){
                            if (StringUtils.isEmpty(strings.get(3))){
                                throw new RuntimeException("电话未填写");
                            }
                            sysCustomer.setPhone(strings.get(3));
                        }
                        //学校
                        else if (j == 4){
                            if (StringUtils.isNotEmpty(strings.get(4))){
                                sysCustomer.setSchool(strings.get(4));
                            }
                        }
                        //所属校区
                        //信息大类
                        else if (j == 6){
                            if (StringUtils.isEmpty(strings.get(6))){
                                throw new RuntimeException("信息大类未填写");
                            }
                            //查询信息大类
                            SourceOfLeadCustomers sourceOfLeadCustomers = sourceOfLeadCustomersService.selectSourceOfLeadCustomersByName(strings.get(6));
                            if (null == sourceOfLeadCustomers){
                                throw new RuntimeException("不存在此信息类");
                            }
                            sysCustomer.setSourceOfLeadCustomersId(sourceOfLeadCustomers.getId());
                        }
                        //信息小类
                        else if (j == 7){
                            if (StringUtils.isEmpty(strings.get(7))){
                                throw new RuntimeException("信息来源小类未填写");
                            }
                            //查询信息小类
                            SourceSubcategory sourceSubcategory = sourceSubcategoryService.selectSourceSubcategoryByNameAndLeadId(strings.get(7), sysCustomer.getSourceOfLeadCustomersId());
                            if (null == sourceSubcategory){
                                throw new RuntimeException("此来源小类不存在此来源大类中");
                            }
                            sysCustomer.setSourceSubcategoryId(sourceSubcategory.getId());
                        }
                        //上传者与创建者
                        else if (j == 8){
                            if (StringUtils.isEmpty(strings.get(8))){
                                //创建者
                                sysCustomer.setCreateBy(SecurityUtils.getUsername());
                                //上传者
                                sysCustomer.setUpBy(SecurityUtils.getUsername());
                            }
                            else {
                                //创建者
                                sysCustomer.setCreateBy(SecurityUtils.getUsername());
                                //上传者
                                sysCustomer.setUpBy(SecurityUtils.getUsername());
                            }
                        }
                        //电话
                        else if (j == 10){
                            if (StringUtils.isNotEmpty(strings.get(10))){
                                sysCustomer.setPhone(strings.get(10));
                            }
                        }
                        //创建时间
                        sysCustomer.setCreateTime(DateUtils.getNowDate());
                        //线索客户性别
                        sysCustomer.setSex(0L);
                        //签约状态
                        sysCustomer.setStatus(0L);
                        //校区
                        sysCustomer.setCampus(110L);
                        //首次解除时间
                        sysCustomer.setFirstTime(DateUtils.getNowDate());
                    }
                    //客户编码
                    status += this.insertSysCustomer(sysCustomer);
                }
            }
        }
        catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e.getMessage());
        }
        return status;
    }

    /**
     * 批量新增线索客户方法
     * @param sysCustomerList
     * @return
     */
    @Override
    public int batchInsertSysCustomer(List<SysCustomer> sysCustomerList) {
        return sysCustomerMapper.batchInsertSysCustomer(sysCustomerList);
    }

    /**
     * 新增客户档案
     *
     * @param sysCustomer 客户档案
     * @return 结果
     */
    @Override
    @Transactional
    public synchronized int insertSysCustomer(SysCustomer sysCustomer)
    {
        int status = 0;
        try {
            //新增客户档案判空方法
            emptyInserSysCustomer(sysCustomer);

            //构建编号(查询当天最大的编码)
            sysCustomer.setCustomerCode(getSerialNumber());

            //状态
            sysCustomer.setStatus(0L);

            //创建人
            sysCustomer.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
            //创建时间
            sysCustomer.setCreateTime(DateUtils.getNowDate());

            //客户档案新增方法
            status = sysCustomerMapper.insertSysCustomer(sysCustomer);
        }
        catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e.getMessage());
        }
        return status;
    }

    /**
     * 分配线索客户
     * @param sysCustomerList
     * @return
     */
    @Override
    @Transactional
    public int allocationCustomer(List<SysCustomer> sysCustomerList) {
        int status = 0;
        try {
            //分配线索客户判空方法
            emptyAllocationCustomer(sysCustomerList);
            //批量修改方法
            for (int i = 0;i < sysCustomerList.size();i++){
                SysCustomer sysCustomer = sysCustomerList.get(i);
                int num = 0;
                //查询线索客户
                SysCustomer querySysCustomer = this.selectSysCustomerByCustomerId(sysCustomer.getCustomerId());
                //修改线索客户方法
                querySysCustomer.setEducationalAdviser(sysCustomer.getEducationalAdviser());
                num = this.updateSysCustomer(querySysCustomer);
                if (num == 0){
                    throw new RuntimeException("替换线索客户失败");
                }
                status += num;
            }
        }
        catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e.getMessage());
        }
        return status;
    }

    /**
     * 分配线索客户判空方法
     * @param sysCustomerList
     */
    @Override
    public void emptyAllocationCustomer(List<SysCustomer> sysCustomerList) {
        //判空主键
        if (null == sysCustomerList){
            throw new RuntimeException("未传输线索客户集");
        }
        //判断主键是否为空
        for (int i = 0;i < sysCustomerList.size();i++){
            SysCustomer sysCustomer = sysCustomerList.get(i);
            if (null == sysCustomer){
                throw new RuntimeException("未传输线索客户");
            }
        }
    }

    /**
     * 获取流水号
     * @return
     */
    @Override
    public String getSerialNumber() {
        String serialNumber = "";

        //今天的日期
        String today = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        //下一级流水号
        int nextSequence;
        int maxSequenceFromDB = getMaxSequenceFromDB(today);

        maxSequenceFromDB += 1;

        //对流水号前拼接流水号
        serialNumber = String.valueOf(maxSequenceFromDB);
        if (serialNumber.length() < 5){
            nextSequence = 5 - serialNumber.length();
            for (int i = 0;i < nextSequence;i++){
                serialNumber = "0" + serialNumber;
            }
        }
        serialNumber = today + serialNumber;
        return serialNumber;
    }

    /**
     * 查询当天最大流水
     * @param date
     * @return
     */
    @Override
    public int getMaxSequenceFromDB(String date) {
        //默认值(当天无记录)
        int maxSeq = 0;
        //查询当天最大流水号
        String sequence = selectCustomerByDate(date);
        if (null != sequence){
            maxSeq = Integer.parseInt(sequence);
        }
        return maxSeq;
    }

    /**
     * 根据当前日期查询客户
     * @param date
     * @return
     */
    @Override
    public String selectCustomerByDate(String date) {
        return sysCustomerMapper.selectCustomerByDate(date);
    }

    /**
     * 新增客户档案判空方法
     * @param sysCustomer
     * @return
     */
    @Override
    public void emptyInserSysCustomer(SysCustomer sysCustomer) {
        //姓名
        if (StringUtils.isEmpty(sysCustomer.getCustomerName())){
            throw new RuntimeException("线索客户名称未填写");
        }
        //性别
        if (sysCustomer.getSex() == null){
            throw new RuntimeException("线索客户性别未填写");
        }
        //所属校区
        if (sysCustomer.getCampus() == null){
            throw new RuntimeException("线索客户校区未选择");
        }
        //年级
        if (null == sysCustomer.getGrade()){
            throw new RuntimeException("线索客户年级未选择");
        }
        //线索客户来源
        if (null == sysCustomer.getSourceOfLeadCustomersId()){
            throw new RuntimeException("线索客户客户来源未选择");
        }
        //首次接触日期
        if (null == sysCustomer.getFirstTime()){
            throw new RuntimeException("先选客户首次接触日期未填写");
        }
        //教育顾问
        /*if (null == sysCustomer.getEducationalAdviser()){
            throw new RuntimeException("教育顾问未选择");
        }*/
    }

    /**
     * 修改客户档案
     *
     * @param sysCustomer 客户档案
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSysCustomer(SysCustomer sysCustomer)
    {
        int status = 0;
        try {
            //修改方法判断
            emptyUpdateSysCustomer(sysCustomer);
            //修改人
            //sysCustomer.setUpdatedBy(SecurityUtils.getUsername());
            //修改时间
            sysCustomer.setUpdatedTime(DateUtils.getNowDate());

            //线索客户修改方法
            status = sysCustomerMapper.updateSysCustomer(sysCustomer);
        }
        catch (Exception e){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(e.getMessage());
        }
        return status;
    }

    /**
     * 修改客户档案判断方法
     * @param sysCustomer
     */
    @Override
    public void emptyUpdateSysCustomer(SysCustomer sysCustomer) {
        //查询是否存在此客户
        SysCustomer querySysCustomer = this.selectSysCustomerByCustomerId(sysCustomer.getCustomerId());
        if (null == querySysCustomer){
            throw new RuntimeException("当前线索客户未查询到");
        }
        //客户名称
        if (null == sysCustomer.getCustomerName()){
            throw new RuntimeException("线索客户名称不可为空");
        }
        //年级
        if (null == sysCustomer.getGrade()){
            throw new RuntimeException("年级不可为空");
        }
        //线索客户来源
        if (null == sysCustomer.getSourceOfLeadCustomersId()){
            throw new RuntimeException("线索客户来源不可为空");
        }
        //首次接触时间
        if (sysCustomer.getFirstTime().compareTo(querySysCustomer.getFirstTime()) != 0){
            throw new RuntimeException("首次接触时间不可修改");
        }
    }

    /**
     * 批量删除客户档案
     *
     * @param customerIds 需要删除的客户档案主键
     * @return 结果
     */
    @Override
    public int deleteSysCustomerByCustomerIds(Long[] customerIds)
    {
        return sysCustomerMapper.deleteSysCustomerByCustomerIds(customerIds);
    }

    /**
     * 删除客户档案信息
     *
     * @param customerId 客户档案主键
     * @return 结果
     */
    @Override
    public int deleteSysCustomerByCustomerId(Long customerId)
    {
        return sysCustomerMapper.deleteSysCustomerByCustomerId(customerId);
    }
}